<template>
  <!-- 单据结构  -->
  <div>
    <div class="data-filter">
      <data-filter
        :filter-items="dataSource.tableHeader"
        @search="doSearch"
      />
    </div>
    <div class="extend-handle">
      <div class="extend-handle-left">
        <el-button
          v-authorityHandle="'structure:add'"
          class="handle-btn "
          color="#4a78bd"
          style="color: #666"
          plain
          @click="addRow"
        >
          新增
        </el-button>

        <el-button
          v-authorityHandle="'structure:import'"

          class="handle-btn mr12"
          color="#4a78bd"
          style="color: #666"
          plain
          @click="addDetail"
        >
          导入明细
        </el-button>
        <el-upload
          v-authorityHandle="'structure:importExcel'"
          class="inline-block"
          accept=".xlsx, .xls"
          :on-change="fileChoice"
          :show-file-list="false"
          :auto-upload="false"
        >
          <el-button
            class="handle-btn"
            color="#4a78bd"
            style="color: #666"
            plain
          >
            导入Excel
          </el-button>
        </el-upload>
        <el-button
          v-authorityHandle="'structure:delete'"
          class="handle-btn-delete ml12"
          color="#f56c6c"
          plain
          style="color: #666"
          @click="deleteRow"
        >
          删除
        </el-button>
      </div>
    </div>
    <v-table
      ref="table"
      need-end-handle
      need-check-box
      need-customize-cell-renderer
      row-key="roleId"
      :end-handle-width="350"
      :total="dataSource.total"
      :current-page="dataSource.currentPage"
      :page-size="dataSource.pageSize"
      :table-data="dataSource.tableData"
      :columns="dataSource.tableHeader"
      :loading="loading&&!editControlCommon.isShow"
      :default-end-handle="false"
      :customize-end-handle="customizeEndHandle"
      :for-mat-data="dataSource.forMatData"
      :customize-cell-renderer="customizeCellRenderer"
      @selectionChange="dataSource.selectionChange($event,dataSource,proxy.$refs.table)"
      @refresh="dataSource.initData(dataSource, proxy.$refs.table)"
      @editRow="goCompile"

      @current-change="dataSource.currentPageChange($event,dataSource,proxy.$refs.table)"
      @sizeChange="dataSource.pageSizeChange($event,dataSource,proxy.$refs.table)"
      @editTableHeader="isShowEditTableHeader = true"
    />
    <el-drawer
      v-model="isShowEditTableHeader"
      :show-close="false"
    >
      <template #header="{ titleId, titleClass }">
        <h4 :id="titleId" :class="titleClass">
          通过拖拽设置您喜欢的表头顺序
        </h4>
        <el-button type="danger" @click="isShowEditTableHeader = false">
          <el-icon class="el-icon--left">
            <CircleCloseFilled />
          </el-icon>
          关闭
        </el-button>
      </template>
      <template #default>
        <div>
          <dynamicHeader
            :is-show-edit-table-header="isShowEditTableHeader" :modules="'role'"
          />
        </div>
      </template>
    </el-drawer>
    <selectDialogForm
      v-if="editControlCommon.isShow"
      ref="dialogForm"
      :width="'60%'"
      :loading="loading"
      :my-client="myClient"
      :form-data="formData"
      :is-show="editControlCommon.isShow"
      :title="'请填写相关信息'"
      :form-input-el="editControlCommon.formInputEl"
      :form-select-el="editControlCommon.formSelectEl"
      :form-text-area-el="editControlCommon.formTextAreaEl"
      :form-upload-el="editControlCommon.formUploadEl"
      :form-time-and-number="editControlCommon.formTimeAndNumber"
      @close-dialog="editControlCommon.isShow=false"
      @emitOpenDialog="editControlCommon.emitOpenDialog"
      @inputDone="editControlCommon.inputDone"
    />
    <selectDialogTable
      v-if="selectTableData.isShow"
      ref="dialogSearch"
      :need-selection="selectTableData.useChoose"
      :use-choose="selectTableData.useChoose"
      :append-table-style="{ background: '#126f9e', color: '#fff', borderColor: 'rgba(192, 192, 192,.5)' }"
      :width="'60%'"
      :search-input-placeholder="selectTableData.searchPlaceholde"
      :is-show="selectTableData.isShow"
      :data-source="selectTableData.dataSource"
      :title="'选择数据'"
      is-show-search-input
      :loading="loading"
      @close-dialog="selectTableData.isShow=false"
      @doDialogSearch="selectTableData.doSearch"
      @chooseRow="selectTableData.chooseRow"
      @submit="selectTableData.chooseRow"
    />
  </div>
</template>

<script setup>
import { pbRequest } from "@/applications/sys/public/pbRequest/index"
import selectDialogForm from '@/components/public/selectDialogForm.vue'
import selectDialogTable from '@/components/public/selectDialogTable.vue'
import dynamicHeader from '@/components/public/dynamicHeader.vue'
import VTable from '@/components/public/virtualTable.vue'
import dataFilter from '@/components/public/dataFilter.vue'
import { DataSource, loading } from './utils/structure'
import { ref, reactive, getCurrentInstance, onBeforeMount, h, resolveDirective, withDirectives } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElButton } from 'element-plus'
import client from '@/utils/upload/upLoadClient'
const router = useRouter()
const route = useRoute()
const authority = resolveDirective('authority')
const myClient = ref(client)
const { proxy } = getCurrentInstance()
const isShowEditTableHeader = ref(false)
const dataSource = ref(null)

const initDataSource = () => {
  dataSource.value = new DataSource({
    modules: 'structure',
    selectUri: '/colorful-fog/orderTable/select'
  })
  dataSource.value.initTableHeader()
  dataSource.value.initData(this, proxy.$refs.table)
}

onBeforeMount(() => {
  initDataSource()
})

const addRow = async () => {
  formData.value = { }
  editControlCommon.isShow = true
}

const goCompile = async (rowData) => {
  formData.value = rowData
  editControlCommon.isShow = true
}

const doSearch = (data) => {
  dataSource.value.search(data, this, proxy.$refs.table)
}

const customizeEndHandle = (rowData) => {
  if (rowData.admin){
    return [h('div', { class: 'table-handel-div no-options' }, '暂无操作')]
  }
  return [h('div', { class: 'table-handel-div' }, [
    withDirectives(h(
      ElButton,
      { class: 'hover-animation', onClick: () => { goCompile(rowData) }, title: '编辑', type: "primary", icon: "Edit", text: true, style: 'padding:0;margin:0;background:transparent' },
      { default: () => "" }), [[authority, 'structure:update']]
    ), withDirectives(h(
      ElButton,
      { class: 'hover-animation', onClick: () => { deleteRow(rowData) }, title: '删除', type: "danger", icon: "Delete", text: true, style: 'padding:0;margin:0;background:transparent' },
      { default: () => "" }), [[authority, 'structure:delete']]
    ), withDirectives(h(
      ElButton,
      { class: 'hover-animation', onClick: () => { addDetail(rowData) }, title: '导入明细', style: 'padding:0;margin:0;background:transparent;width:80px;color:#0c81b1;margin-right:10px' },
      { default: () => "导入明细" }), [[authority, 'structure:import']]
    ), withDirectives(h(
      ElButton,
      { class: 'hover-animation', onClick: () => { updateDetail(rowData) }, title: '更新明细', style: 'padding:0;margin:0;background:transparent;width:80px;color:#0c81b1;margin-right:10px' },
      { default: () => "更新明细" }), [[authority, 'structure:update']]
    ), withDirectives(h(
      ElButton,
      { class: 'hover-animation', onClick: () => { checkDetail(rowData) }, title: '查看明细', style: 'padding:0;margin:0;background:transparent;width:80px;color:#0c81b1' },
      { default: () => "查看明细" }), [[authority, 'structure:check']]
    )
  ])]
}

let row = null

const addDetail = (rowData) => {
  if (!rowData.id && dataSource.value.selections.length === 0){
    proxy.$message.error('请选择数据')
    return
  }
  row = rowData
  openSelectDialog('dataSource')

}

const updateDetail = (rowData) => {
  if (!rowData.id && dataSource.value.selections.length === 0){
    proxy.$message.error('请选择数据')
    return
  }

  proxy.$alert('是否确认更新明细？', '提示', {
    type: 'info',
    icon: 'InfoFilled',
    confirmButtonText: '确定',
    callback: (action) => {
      if (action === 'confirm') {
        let params = rowData.orderTable ? rowData.orderTable : dataSource.value.selections.map(item => item.orderTable)
        dataSource.value.updateTableFiled(params).then(res => {
          if (res.code === 200){
            proxy.$alert('更新成功', '提示', {
              type: 'success',
              icon: 'InfoFilled',
              showCancelButton: false,
              callback: () => {
                dataSource.value.initData(this, proxy.$refs.table)
              }
            })
          }
        })
      }
    }
  })

}

const checkDetail = (rowData) => {
  router.push(`/detail/strucitureDetail?id=${rowData.id}&orderTable=${rowData.orderTable}&title=${route.meta.title}`)
}

const formData = ref({})

const editControlCommon = reactive({
  isShow: false,
  formInputEl: [
    {
      title: "单据名称",
      key: 'orderName',
      element: 'input',
      rules: [{
        required: true,
        message: '该项不能为空',
        trigger: 'blur'
      }]
    }, {
      title: "单据关联表",
      key: 'orderTable',
      element: 'input'
    }, {
      title: "单据关联表名称",
      key: 'orderTableName',
      element: 'input'
    }, {
      title: "所属主表",
      key: 'orderMainTable',
      element: 'input'
    }, {
      title: "外键",
      key: 'orderForeign',
      element: 'input'
    }, {
      title: "外键名称",
      key: 'orderForeignName',
      element: 'input'
    }
  ],
  formSelectEl: [{
    title: "类型",
    key: 'type',
    element: 'radio',
    options: [{
      label: '主表',
      value: 'MAIN'
    }, {
      label: '明细',
      value: 'DETAIL'
    }],
    rules: [{
      required: true,
      message: '该项不能为空',
      trigger: 'blur'
    }]
  }],
  formTextAreaEl: [{
    title: "备注",
    key: 'comment',
    element: 'input',
    type: 'textarea'
  }],
  formTimeAndNumber: [],
  emitOpenDialog: (val) => {
    console.log(val)
  },
  inputDone: (val) => {

    proxy.$alert('是否确认提交？', '提示', {
      type: 'info',
      icon: 'InfoFilled',
      confirmButtonText: '确定',
      callback: (action) => {
        if (action === 'confirm') {
          if (val.id){
            dataSource.value.updateStructure([val]).then((res) => {
              if (res.code === 200){
                editControlCommon.isShow = false
                proxy.$message.success('更新成功')
                dataSource.value.initData(this, proxy.$refs.table)
              }
            })
          } else {

            dataSource.value.addStructure(val).then((res) => {
              if (res.code === 200){
                editControlCommon.isShow = false
                proxy.$message.success('新增成功')
                dataSource.value.initData(this, proxy.$refs.table)
              }
            })
          }
        }
      }
    })

  }
})

const customizeCellRenderer = ({ forMatValue, rowIndex, column, rowData }) => {
  return forMatValue
}

const deleteRow = async (rowData) => {
  if (!rowData.id && dataSource.value.selections.length === 0){
    proxy.$message.error('请选择数据')
    return
  }
  proxy.$alert('是否确认删除？', '提示', {
    type: 'error',
    icon: 'InfoFilled',
    confirmButtonText: '确定',
    callback: (action) => {
      if (action === 'confirm') {
        let params = rowData.id ? [rowData.id] : dataSource.value.selections.map(item => item.id)
        dataSource.value.deleteStructure(params).then(res => {
          if (res.code === 200){
            proxy.$alert('删除成功', '提示', {
              type: 'success',
              icon: 'InfoFilled',
              showCancelButton: false,
              callback: () => {
                dataSource.value.initData(this, proxy.$refs.table)
              }
            })
          }
        })
      }
    }
  })
}

const handleXlsxData = (file) => {
  return file.map((item) => {
    return {
      orderName: item['单据名称'],
      orderTable: item['单据关联表'],
      orderTableName: item['单据关联表名称'],
      orderMainTable: item['所属主表'],
      orderForeign: item['外键'],
      orderForeignName: item['外键名称'],
      type: item['类型'] === '主表' ? 'MAIN' : 'DETAIL',
      comment: item['备注']
    }
  })

}

const fileChoice = async (file) => {
  let dataTool = new proxy.$DataTool()
  let xlsxData = await dataTool.xlsx2DataObject(file.raw)
  let data = handleXlsxData(xlsxData)
  proxy.$alert('是否确认导入？', '提示', {
    type: 'info',
    icon: 'InfoFilled',
    confirmButtonText: '确定',
    callback: (action) => {
      if (action === 'confirm') {
        dataSource.value.addStructureBatch(data).then(res => {
          if (res.code === 200){
            proxy.$alert('导入成功', '提示', {
              type: 'success',
              icon: 'InfoFilled',
              showCancelButton: false,
              callback: () => {
                dataSource.value.initData(this, proxy.$refs.table)
              }
            })
          }
        })
      }
    }
  })
}

const openSelectDialog = async (name) => {
  switch (name){
  case 'dataSource': {
    selectTableData.useChoose = false
    selectTableData.chooseRow = (val) => {

      proxy.$alert('是否确认导入明细？', '提示', {
        type: 'info',
        icon: 'InfoFilled',
        confirmButtonText: '确定',
        callback: (action) => {
          if (action === 'confirm') {
            let params = {
              tableNameList: row.orderTable ? [row.orderTable] : dataSource.value.selections.map(item => item.orderTable),
              dataSourceId: val.id
            }
            if (row.orderTable){
              dataSource.value.addTableField(params).then(res => {
                if (res.code === 200){
                  proxy.$alert('导入成功', '提示', {
                    type: 'success',
                    icon: 'InfoFilled',
                    showCancelButton: false,
                    callback: () => {
                      dataSource.value.initData(this, proxy.$refs.table)
                    }
                  })
                }
              })
              return
            }
            dataSource.value.addTableFields(params).then(res => {
              if (res.code === 200){
                proxy.$alert('导入成功', '提示', {
                  type: 'success',
                  icon: 'InfoFilled',
                  showCancelButton: false,
                  callback: () => {
                    dataSource.value.initData(this, proxy.$refs.table)
                  }
                })
              }
            })
          }
        }
      })
      selectTableData.isShow = false
    }
    selectTableData.doSearch = (val) => {
      selectTableData.dataSource.initData()
    }
    selectTableData.dataSource = new DataSource({
      selectUri: `/colorful-fog/dataSource/list`,
      tableHeader: [{
        label: "数据库名称",
        prop: "sourceName",
        width: 200
      }, {
        label: "数据库Code",
        prop: "sourceCode",
        width: 200
      }],
      pageSize: 10
    })

    selectTableData.dataSource.forMatData = (row, column) => {
      return row[column.property] ?? '-'
    }
    selectTableData.dataSource.initData = async (context = selectTableData.dataSource) => {
      let { data: { data, code, message } } = await pbRequest.post(`${context.selectUri}?currentPage=${context.currentPage}&pageSize=${context.pageSize}`, context.searchData)
      if (code !== 200) return
      context.total = data.length
      context.tableData = data
    }
    await selectTableData.dataSource.initData()
    selectTableData.isShow = true
    return
  }

  default: return
  }
}

const selectTableData = reactive({
  isShow: false,
  dataSource: null,
  searchPlaceholde: '',
  doSearch: (val) => {
    console.log(val)
  },
  chooseRow: (val) => {
    console.log(val)
  }
})
</script>

<style lang="less" scoped>
.table{
  padding: 10px;
  background-color: #ffffff;
}
</style>
